package controller.admin.employee;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import model.DTO.EmployeeLoginDTO;
import model.VO.EmployeeLoginVO;
import model.entity.Employee;
import service.Impl.EmployeeServiceImpl;
import util.Encrypt;
import util.GetJsonUtil;
import util.JwtUtils;
import util.ResultUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@WebServlet("/admin/employee/login")
public class EmployeeLoginController extends HttpServlet {
    //员工登录
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从前端获取登录信息
        EmployeeLoginDTO employeeLoginDTO= (EmployeeLoginDTO) GetJsonUtil.get(req,new EmployeeLoginDTO());
        EmployeeServiceImpl service=new EmployeeServiceImpl();
        employeeLoginDTO.setPassword(Encrypt.toMd5(employeeLoginDTO.getPassword()));
        System.out.println(employeeLoginDTO.getPassword());
        //从数据库查询对应信息
        Employee employee=service.Find(employeeLoginDTO.getUsername());
        EmployeeLoginVO employeeLoginVO=new EmployeeLoginVO();
        //比对
        if(Objects.equals(employee.getPassword(), employeeLoginDTO.getPassword())){
            employeeLoginVO.setId(employee.getId());
            employeeLoginVO.setName(employee.getName());
            employeeLoginVO.setUserName(employee.getUsername());

            Map<String,Object> claims=new HashMap<>();
            claims.put("id",employee.getId());
            String jwt=JwtUtils.generateJwt(claims);
            employeeLoginVO.setToken(jwt);
            //将登录员工的部分信息传给前端
            String json=ResultUtil.getJSON(employeeLoginVO);
            resp.getWriter().write(json);

        }
        else {
            resp.getWriter().write("登录失败!");
        }

    }
}
